﻿using System;
using Comdiv.QWeb.Binding;

namespace Comdiv.QWeb.Factory {
	public class ActionTypeDescriptor {
		private Type binderType;
		private bool? supportsBind;

		public ActionTypeDescriptor(Type type) {
			ActionType = type;
		}

		public Type ActionType { get; set; }
		public IQWebFactory Factory { get; set; }

		public bool SupportsBind {
			get {
				if (supportsBind.HasValue) {
					return supportsBind.Value;
				}
				lock (this) {
					supportsBind = false;
					foreach (var binder in Factory.GetBinders()) {
						if (binder.IsBindable(ActionType)) {
							supportsBind = true;
							binderType = binder.GetType();
						}
					}
					return supportsBind.Value;
				}
			}
		}

		public BindAttribute[] Binders { get; set; }

		public Type GetBinderType() {
			if (!SupportsBind) {
				return null;
			}
			return binderType;
		}

		public IActionBinder GetBinder() {
			return Factory.GetBinder(binderType);
		}
	}
}